package cn.gson.crm.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 公共servlet
 */

public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	protected void forward(String page) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/jsp/" + page).forward(request, response);
	}

	protected void erroForward(String page, String message) throws ServletException, IOException {
		request.setAttribute("erro", message);
		forward(page);
	}
	
	protected void redirect(String path) throws IOException{
		String basePath = (String) request.getAttribute("basePath");
		response.sendRedirect(basePath+path);
	}

	protected void showErro(Exception e) throws ServletException, IOException{
		showErro(e.getMessage());
	}
	protected void showErro(String message) throws ServletException, IOException{
		request.setAttribute("message", message);
		forward("erro.jsp");
	}
	
	protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		setResponseAndResquest(request, response);
		String method = request.getMethod();
		
			try {
				if(method.equalsIgnoreCase("get")){
				get(request,response);
				}
				else if(method.equalsIgnoreCase("post")){
					post(request,response);
				}
			} catch (Exception e) {
				e.printStackTrace();
				showErro(e);
			}
		
	}
	
	protected void get(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.getWriter().append("请重写get请求");
	}
	
	protected void post(HttpServletRequest request,HttpServletResponse response) throws IOException{
		response.getWriter().append("请重写post请求");
	}
	
	private void setResponseAndResquest(HttpServletRequest request,HttpServletResponse response){
		this.request = request;
		this.response = response;
	}
}
